package com.moon.admin.flowable.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.FormService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.form.StartFormData;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.moon.admin.flowable.entity.FlowFormModelEntity;
import com.moon.admin.flowable.mapper.FlowFormModelMapper;
import com.moon.admin.framework.util.MoonException;

/**
 * 自定义表单
 * @author ninglong
 * @create 2020-09-27 14:14
 */
@Service
public class FlowFormModelService extends ServiceImpl<FlowFormModelMapper, FlowFormModelEntity>{

	@Autowired
    private FormService formService;
	@Autowired
    private ProcessEngine processEngine;

    /**
     * 获取任务节点表单
     * @param taskId
     * @param processInstanceId
     * @return
     */
    public Map<String, Object> getFormInfoByTaskIdAndProcessInstanceId(String taskId, String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        //获取节点关联的表单
        HistoricTaskInstance hisTask = processEngine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        String formKey = "";String processDefinitionId = "";
        if(hisTask!=null) {
        	formKey = hisTask.getFormKey();
        }
        //如果当前任务未关联表单，则历史节点关联的表单
        if(hisTask==null || StringUtils.isBlank(formKey)) {
        	 List<HistoricTaskInstance> historicTaskInstances = processEngine.getHistoryService()
             		.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).finished()
             		.orderByHistoricTaskInstanceEndTime().desc().list();
             for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
            	 processDefinitionId = historicTaskInstance.getProcessDefinitionId();
                 if(StringUtils.isNotBlank(historicTaskInstance.getFormKey())){
                     formKey = historicTaskInstance.getFormKey();
                 }
             }
        }
        //如果当前任务未关联表单，则开始节点关联的表单
        if(StringUtils.isBlank(formKey)) {
        	StartFormData startForm = formService.getStartFormData(processDefinitionId);
        	formKey = startForm.getFormKey();
        }
        if(StringUtils.isBlank(formKey)){
        	throw new MoonException("任务节点未关联表单");
        }
        //获取个人任务表单
        FlowFormModelEntity formModel = this.baseMapper.selectOne(Wrappers.<FlowFormModelEntity>lambdaQuery().eq(FlowFormModelEntity::getFormKey,formKey).last("limit 1"));
        result.put("formModel",formModel.getFormSchema());
        result.put("formKey", formModel.getFormKey());
        //获取变量
		List<HistoricVariableInstance> list = processEngine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
		Map<String,Object> variables = Maps.newHashMap();
		for (int i = 0; i < list.size(); i++) {
			HistoricVariableInstance historicVariableInstance = list.get(i);
			variables.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
		}
        result.put("variables",variables);
        return result;
    }

    /**
     * 获取开始节点的表单
     * @return
     */
    public Map<String, Object> getStartFormInfoByDeploymentId(String deploymentId) {
        Map<String, Object> result = new HashMap<>();
        ProcessDefinition pd = processEngine.getRepositoryService().createProcessDefinitionQuery()
				.deploymentId(deploymentId).latestVersion()
				.singleResult();
        StartFormData startForm = formService.getStartFormData(pd.getId());
        if(StringUtils.isBlank(startForm.getFormKey())){
        	throw new MoonException("开始节点未关联表单");
        }
    	FlowFormModelEntity formModel = this.baseMapper.selectOne(Wrappers.<FlowFormModelEntity>lambdaQuery().eq(FlowFormModelEntity::getFormKey,startForm.getFormKey()).last("limit 1"));
        result.put("formModel",formModel.getFormSchema());
        result.put("formKey", startForm.getFormKey());
        return result;
    }
}